// PresetsController.js
// ====================

var helper = require('./helper');

/* configuration array */
var presets = require('./conf/presets');
var config = require('./conf/config');
var logger = require('./logger');
var fs = require('fs');

module.exports = {
	/* returnes a preset for a given filetype */
	getPresets: function(type) {
		var presetsArray = [];
	
		presets.forEach(function(item) {
			if (item.types.indexOf(type)!=-1) {
			
				/* check preset */
				if (typeof item.priority == "undefined") {
					item.priority = 99;
				}
			
				presetsArray.push(item);
			}
		});
		
		if (presetsArray.length==0) {
			logger.error('No preset for extension '+type+' found');
		}
		
		/* sort by priority and return*/
		return presetsArray.sort(this.sortPresets);
	},
	
	/* sorts an array of presets */
	sortPresets: function(a,b) {
	
  		if (a.priority < b.priority)
		     return -1;
		if (a.priority > b.priority)
    		return 1;
  		
  		return 0;
	},
	
	/* execute one presets after the other! */
	executePresets: function(presetsArray, source, destination_template, callback) {
		
		if (presetsArray.length==0) {
			callback(false);
			return;
		}
		
		var tmp=this;
		var preset = presetsArray.pop();
		var full_destination = destination_template+'.'+preset.destType;

		
		this.executePreset(preset,source,full_destination,function(result) {

			if (result!=true) {
				tmp.executePresets(presetsArray,source,destination_template,callback);
			}
			else {
				callback(full_destination);
			}
		});
		
	},
	
	/* converts a source file using the given converter preset */
	executePreset: function(preset, source, destination, callback) {
		
		try {
			/* clean destination file */
			fs.unlink(destination,function() {});
		
			/* execute converter */
			var spawn = require('child_process').spawn;
			var command = [];
			
			preset.converterCmnd.split(' ').forEach(function(v) {
				
				v = helper.replaceStrings(v,{
					'source': source,
					'destination': destination
				});
				command.push(v);
				
			});
			
			logger.debug('Will execute '+command.join(' '));
			
			if (preset.preFlight!=undefined) {
				logger.debug('Running preflight function');
				preFlightResult=preset.preFlight(source);
				
				if (preFlightResult===false) {
					logger.debug('Preflight reported an error => exiting');
					callback(false);
					return;
				}
				
			}
			
			var proc = spawn(command.shift(),command, {
				'cwd': process.cwd(),
				'env': { 'PATH': config.envPathVariable }
			});
			proc.stdout.on('data', function(data) { logger.debug(data) });
			proc.stderr.on('data', function(data) { logger.debug(data) });
			proc.on('exit', function(code) {
				logger.debug('Converter exited with code '+code);
				if (code==0) {
					
					if (preset.postFlight!=undefined) {
						logger.debug('Running postflight function');
						preset.postFlight(destination);
					}
				
					callback(true);
				}
				else {
					callback(false);
				}
			});
			
		}
		catch(err) {
			logger.error('Error while executing converter: '+err);
			callback(false);
			return;
		}
		
		return;
	}
};
